import axios from 'axios';
import type { AxiosRequestConfig } from 'axios';
import { getToken } from '@/utils/auth';
import { Message } from '@arco-design/web-vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

// import useGlobalParametersStore from '@/stores/globalParameters';
// const globalParameters = useGlobalParametersStore();

const env = import.meta.env;
const service = axios.create({
  timeout: 100000, // 请求超时时间
  baseURL: env.VITE_APP_BASE_URL,
});

type YXRequestConfig = AxiosRequestConfig & {
  headers?: any;
  noToken?: boolean; // 是否不需要token，默认false
  isLoading?: boolean; // 是否请求时开启全局Loading，默认false
  loadingTip?: string; // 全局Loading的提示
  successMsg?: string;
};

// axios请求前拦截
service.interceptors.request.use(
  async (config: YXRequestConfig) => {
    // console.log(config);
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    if (!config.noToken) {
      // 判断是否需要token
      config.headers.Authorization = `${getToken()}`;
    }
    return config;
  },
  (err) => {
    console.log(err);
  }
);

// axios请求后拦截
service.interceptors.response.use(
  function (response) {
    const {
      msg,
      code,
      msgType,
    }: { msg: string; code: number; msgType: string } =
      response.data || response;
    if (code === 200 || code === 0) {
      if (
        (msgType === 'post' || msgType === 'put' || msgType === 'delete') &&
        code === 200
      )
        Message.success(`${msg}`);
      return Promise.resolve(response.data);
    } else {
      Message.error(`${msg}`);
      return Promise.reject(response.data);
    }
  },
  function (error) {
    const status = error.response.status;
    const code = error.response.data.code;
    const msg = error.response.data.msg;
    if (code === 1001) {
      Message.error(`${msg}`);
    } else if (status === 500) {
      Message.error(
        `${status} :${
          msg || error.response.data || '服务器问题，请求失败,联系陈俊升查看'
        }`
      );
    } else if (status === 401) {
      let { pathname, search, origin } = window.location;
      const routeInfo = {
        path: pathname,
        params: {},
      };
      if (search) {
        let params = new URLSearchParams(search);
        params.forEach(function (value, key) {
          routeInfo.params[key] = value;
        });
      }
      localStorage.setItem('historyRoute', JSON.stringify(routeInfo));
      window.location.href = `${origin}/login`;
    } else {
      Message.error(
        `${status} :${msg || error.response.data || '请求失败,联系陈俊升查看'}`
      );
    }
    return Promise.reject(error);
  }
);

// axios封装
export async function ajaxService<T = any>(config: YXRequestConfig) {
  if (config.isLoading) {
    // 判断是否打开全局Loading
    // globalParameters.setLoadingConfig(config.isLoading, config.loadingTip);
  }
  try {
    const res: { data: T } = await service(config);
    if (config.successMsg) Message.success(config.successMsg);
    return Promise.resolve(res.data);
  } catch (err: any) {
    return Promise.reject(err);
  }
}
